//
//  PersonViewController.m
//  Riese
//
//  Created by air on 2019/10/20.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "PersonViewController.h"
#import "JYJCommenItem.h"
#import "UserCell.h"
#import "AddUserCell.h"

#import "AddUserViewController.h"//跳转到添加新的家庭用户
#import "SettingViewController.h"//设置界面
#import "ContactViewController.h"
#import "KnowledgeViewController.h"

@interface PersonViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView*  tableView;
@property(nonatomic,strong)NSDictionary* dataDict;
@property(nonatomic,strong)NSArray*  dataArr;
@property(nonatomic,strong)NSMutableArray*   isOpenArr;
@property(nonatomic,strong)NSArray* sectionNameArr;

@property (nonatomic, strong) UIView * footView;
@property (nonatomic, strong) UILabel * lab_version;
@property (nonatomic, strong) FMDatabase *db;
///** headerIcon */
//@property (nonatomic, weak) UIImageView *headerIcon;
/** data */
@property (nonatomic, strong) NSArray *userArr;

@end

@implementation PersonViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.frame = CGRectMake(0, 0, self.view.width, self.view.height - 30);//self.view.bounds;
    self.footView.sd_layout.leftSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0).widthIs(self.view.width).heightIs(30);
    self.lab_version.sd_layout.leftEqualToView(self.footView).centerYEqualToView(self.footView).widthIs(self.footView.width).heightIs(30);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=UIColorFromHex(0x5CBBC0);
    _sectionNameArr=@[NSLocalizedString(@"Home", nil),NSLocalizedString(@"Your Profile", nil),NSLocalizedString(@"Settings", nil), NSLocalizedString(@"Heart Knowledge", nil), NSLocalizedString(@"Contact Us", nil)];
    
     JYJCommenItem * myHome = [JYJCommenItem itemWithSelectedIcon:@"home_selected" UnSelectedIcon:@"home_unSelected" title:NSLocalizedString(@"Home", nil) subtitle:@"" destVcClass:[UIViewController class] isSelect:YES];

     JYJCommenItem * myProfile = [JYJCommenItem itemWithSelectedIcon:@"per_pro_seleted" UnSelectedIcon:@"per_pro_unSeleted" title:NSLocalizedString(@"Your Profile", nil) subtitle:@"" destVcClass:[AddUserViewController class] isSelect:NO];

     JYJCommenItem * mySetting = [JYJCommenItem itemWithSelectedIcon:@"per_set_selected" UnSelectedIcon:@"per_set_unSelected" title:NSLocalizedString(@"Settings", nil) subtitle:nil destVcClass:[SettingViewController class] isSelect:NO];

     JYJCommenItem * myHeart = [JYJCommenItem itemWithSelectedIcon:@"per_heart_sel" UnSelectedIcon:@"per_heart_unSel" title:NSLocalizedString(@"Heart Knowledge", nil) subtitle:nil destVcClass:[UIViewController class] isSelect:NO];
     
     JYJCommenItem * myContact = [JYJCommenItem itemWithSelectedIcon:@"per_contact_sel" UnSelectedIcon:@"per_contact_unSel" title:NSLocalizedString(@"Contact Us", nil) subtitle:nil destVcClass:[UIViewController class] isSelect:NO];

    self.isOpenArr=[[NSMutableArray alloc] init];
    // self.dataDict=@{@"first":firstDataArr,@"second":secondArr,@"third":thirdArr};
//    self.dataArr=@[firstDataArr,secondArr,thirdArr, firstDataArr, firstDataArr];
    self.dataArr = @[myHome, myProfile, mySetting, myHeart, myContact];
    //for (int i=0; i<self.dataDict.allKeys.count; i++) {
    for (int i=0; i<self.dataArr.count; i++) {
        NSString*  state=@"close";
        [self.isOpenArr addObject:state];
    }
    [self loadTableView];
}
-(void)loadTableView
{
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, SCREEN_HEIGHT - kBottomSafeHeight - 30) style:UITableViewStyleGrouped];
    self.tableView.sectionFooterHeight=0;//从第二个开始，每个section之间的距离
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.backgroundColor = UIColorFromHex(0x5CBBC0);//[UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = UIColorFromHex(0x5CBBC0);//[UIColor colorWithRed:245 / 255.0 green:247 / 255.0 blue:250 / 255.0 alpha:1.0];
        headerView.frame = CGRectMake(0, 0, self.tableView.width, 150);
        self.tableView.tableHeaderView = headerView;
        
        /** 头像图片 */
        UIImageView *headerIcon = [[UIImageView alloc] init];
        headerIcon.image = [UIImage imageNamed:@"person_home_icon"];
        headerIcon.frame = CGRectMake(30, 60, 178, 53);
        [headerView addSubview:headerIcon];
        
        self.footView = [[UIView alloc] init];
        self.footView.backgroundColor = [UIColor whiteColor];
    //    footView.frame  = CGRectMake(0, 0, self.tableView.width, 40);
    //    self.tableView.tableFooterView = footView;
        [self.view addSubview:self.footView];
        self.footView.sd_layout.leftSpaceToView(self.view, 0).bottomSpaceToView(self.view, kBottomSafeHeight).widthIs(self.view.width).heightIs(30);
        
        self.lab_version = [[UILabel alloc] init];
        [self.footView addSubview:self.lab_version];
        self.lab_version.sd_layout.leftEqualToView(self.footView).centerYEqualToView(self.footView).widthIs(self.footView.width).heightIs(30);
        self.lab_version.backgroundColor = UIColorFromHex(0x5CBBC0);
        self.lab_version.text = kCombileABStr(@"Version :", BundleVersion);
        self.lab_version.textColor = UIColorFromHex(0x005894);
        self.lab_version.textAlignment = NSTextAlignmentCenter;
        self.lab_version.font = [UIFont systemFontOfSize:14];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // return self.dataDict.allKeys.count;
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
//        for (int i = 0; i < self.dataArr.count; i++) {
//            JYJCommenItem *item = self.dataArr[i];
//            if (item.isSelected && i != 1) {
//                return 0;
//            }
//        }

        if (self.userArr.count > 0) {
            if (self.userArr.count == 1 && [self.userArr[0] isKindOfClass:[NSString class]]) {
                return 1;
            }
            else {
                return self.userArr.count + 1;
            }
        }
        else {
            return 1;
        }
    }
    
    return 0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.userArr.count && ![self.userArr[0] isKindOfClass:[NSString class]]) {
        NSString* identifer = @"UserCell";
        UserCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:identifer owner:self options:nil].firstObject;
        }
        
        cell.backgroundColor = UIColorFromHex(0x4FA1A5);
        cell.dataDic = self.userArr[indexPath.row];
        cell.editUserBtn.tag = indexPath.row;
        [cell.editUserBtn addTarget:self action:@selector(editUserBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (defaults(@"id")) {
            if ([cell.dataDic[@"id"] integerValue] == [defaults(@"id") integerValue]) {
                cell.selectImgV.image = [UIImage imageNamed:@"user_select"];
            }
            else {
                cell.selectImgV.image = [UIImage imageNamed:@"user_normal"];
            }
        }
        else {
            cell.selectImgV.image = [UIImage imageNamed:@"user_normal"];
        }
        
        return cell;
    }
    else {
        NSString *cellIdentifier = @"AddUserCell";
        AddUserCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
//           0x1D8CD7  0x4FA1A5
        cell.backgroundColor = UIColorFromHex(0x4FA1A5);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && self.userArr.count == 0) {
        return 0;
    }
    else {
        return 50;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.row == self.userArr.count || [self.userArr[0] isKindOfClass:[NSString class]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
        
        AddUserViewController *vc = [AddUserViewController new];
        vc.isEdit = @"0";
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        setDefaults(self.userArr[indexPath.row][@"id"], @"id");
        setDefaults(self.userArr[indexPath.row][@"avatar"], @"avatar");
        setDefaults(self.userArr[indexPath.row][@"nickname"], @"nickname");
        setDefaults(self.userArr[indexPath.row][@"sex"], @"sex");
        setDefaults(self.userArr[indexPath.row][@"age"], @"age");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUser" object:nil];
        [tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
        });
    }
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView*  sectionBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    sectionBackView.backgroundColor= UIColorFromHex(0x5CBBC0);//[UIColor whiteColor];
    
    UIButton*  button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, self.tableView.width, 51)];
    button.tag = 100+section;
    [button addTarget:self action:@selector(ClickSection:) forControlEvents:UIControlEventTouchUpInside];
    [sectionBackView addSubview:button];
    
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(20, 5, self.tableView.width - 40, 40)];
    bgV.backgroundColor = UIColorFromHex(0x5CBBC0);
    bgV.layer.cornerRadius = 20;
    bgV.clipsToBounds = YES;
    bgV.tag = 200 + section;
    bgV.userInteractionEnabled = NO;
    [button addSubview:bgV];
    
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage imageNamed:[self.dataArr[section] icon_unSelected]];
    iconView.tag = 300 + section;
    [bgV addSubview:iconView];
    iconView.sd_layout.leftSpaceToView(bgV,11).centerYEqualToView(bgV).widthIs(15).heightIs(15);
    
    // 2.标题
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.tag = 400 + section;
    nameLabel.text = [self.dataArr[section] title];
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.font = [UIFont systemFontOfSize:15];
    [bgV addSubview:nameLabel];
    nameLabel.sd_layout.leftSpaceToView(iconView, 10).topSpaceToView(bgV, 10).widthIs(bgV.width - iconView.width - 15).heightIs(bgV.height - 10 * 2);
    
    if ([self.dataArr[section] isSelected]) {
        if (section == 1 && self.userArr.count > 0) {
            button.backgroundColor = UIColorFromHex(0x4FA1A5);
        }
        bgV.backgroundColor = [UIColor whiteColor];
        iconView.image = [UIImage imageNamed:[self.dataArr[section] icon_selected]];
        nameLabel.textColor = UIColorFromHex(0x5CBBC0);
    }
        
    return sectionBackView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

#pragma mark - button Click
- (void)editUserBtnClick:(UIButton *)sender {
    AddUserViewController *vc = [AddUserViewController new];
    vc.isEdit = @"1";
    vc.dataDic = self.userArr[sender.tag];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)ClickSection:(UIButton*)sender {
    
    JYJCommenItem *item = self.dataArr[sender.tag - 100];
    
//    JYJPushBaseViewController *vc = [[item.destVcClass alloc] init];
//    vc.title = item.title;
//    vc.animateViewController = (JYJAnimateViewController *)self.parentViewController;
//    [self.parentViewController.navigationController pushViewController:vc animated:YES];
    
    for (int i = 0; i < self.dataArr.count; i++) {
        JYJCommenItem *item1 = self.dataArr[i];
        if (item1.isSelected) {
            item1.isSelected = NO;
            NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:i];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    
    if (sender.tag == 101) {
        if (self.userArr.count == 0) {
            // 创建数据库对象
            NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString * path = [docsdir stringByAppendingPathComponent:@"UserInfo.sqlite"];//将需要创建的串拼接到后面
            self.db = [FMDatabase databaseWithPath:path];
            // 建表
            [self createTable];
        }
    }
    
    item.isSelected = YES;
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:sender.tag-100];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
    
    if (sender.tag == 100) {
        // Home
        [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
    }
    else if (sender.tag == 102) {
        // Settings
        [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
        SettingViewController *vc = [SettingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (sender.tag == 103) {
        // Heart Knowledge
        [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
        KnowledgeViewController *vc = [KnowledgeViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (sender.tag == 104) {
        // Contact Us
        [[NSNotificationCenter defaultCenter] postNotificationName:@"closeAnimate" object:nil];
        ContactViewController *vc = [ContactViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - FMDB
// 创建表
- (void)createTable{

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"userInfo"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT,'avatar' 'text', 'nickname' 'text', 'sex' 'text','age' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self addUserInfo];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self addUserInfo];
           [self.db close];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 查询数据
- (void)addUserInfo {
    FMResultSet *rs = [self.db executeQuery:@"select * from userInfo"];
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    // 遍历结果集
    while ([rs next]) {
        NSDictionary *dic = @{@"id": [rs stringForColumn:@"ID"],@"avatar": [rs stringForColumn:@"avatar"], @"nickname": [rs stringForColumn:@"nickname"], @"sex": [rs stringForColumn:@"sex"], @"age": [rs stringForColumn:@"age"]};
        [arr addObject:dic];
    }
    
    self.userArr = [NSArray arrayWithArray:arr];
    if (self.userArr.count == 0) {
        self.userArr = @[@"Add"];
    }
}

/**
 判断一张表是否已经存在
 @param tablename 表名
 */
- (BOOL)isExistTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM sqlite_master where type= 'table' and name= '%@';",tablename];
    FMResultSet *rs = [self.db executeQuery:sql];
//    BOOL result = [db executeQuery:sql];
    while ([rs next]) {
        NSInteger count = [rs intForColumnIndex:0];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
